package reflect;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

//使用指定构造器实例化对象
public class ReflectDemo3 {
    public static void main(String[] args) throws ClassNotFoundException, InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchMethodException {
        Person p=new Person("李四");
        System.out.println(p);
        //1获取类对象;
        Class cls=Class.forName("reflect.Person");
        Constructor[] cs=cls.getConstructors();
        System.out.println("一共有:"+cs.length+"个构造器");

            /*
            2通过类对象获取对应的构造器
            Constructor类，称为构造器对象，也是反射对象之一
            它的每一个实例用于表示某个类某的某个特定的构造器
         */
//        Constructor c = cls.getConstructor();//不传参数时获取的就是无参构造器
//        Object obj = c.newInstance();//new Person();
        //获取Person(String name)
        Constructor c = cls.getConstructor(String.class);
        Object obj = c.newInstance("王五");//new Peron("王五")
        System.out.println(obj);

        Constructor c2= cls.getConstructor(String .class,int .class);
        Object obj2=c2.newInstance("赵六",20);
        System.out.println(obj2);
    }
}
